<template>
  <div class="common-layout">
    <el-container>
      <el-aside width="200px">
        <el-affix :offset="10">
          <el-radio-group v-model="isCollapse" style="margin-bottom: 20px">
            <el-radio-button :value="false">展开</el-radio-button>
            <el-radio-button :value="true">折叠</el-radio-button>
          </el-radio-group>
          <el-menu default-active="1" class="el-menu-vertical-demo" :collapse="isCollapse" @open="handleOpen"
            @close="handleClose">
            <el-menu-item index="/index">
              <el-icon>
                <House />
              </el-icon>
              <template #title>首页</template>
            </el-menu-item>
            <el-menu-item index="/booklist">
              <el-icon>
                <Folder />
              </el-icon>
              <template #title>图书列表</template>
            </el-menu-item>
            <el-menu-item index="/booksales">
              <el-icon>
                <Reading />
              </el-icon>
              <template #title>图书售卖</template>
            </el-menu-item>
            <el-menu-item index="/help">
              <el-icon>
                <Warning />
              </el-icon>
              <template #title>帮助</template>
            </el-menu-item>
          </el-menu>
          <!-- 路由出口，用于显示当前路由对应的组件 -->
          <router-view></router-view>
        </el-affix>
      </el-aside>
      <el-container>
        <el-affix :offset="0">
          <el-header style="
              display: flex;
              align-items: center;
              height: 60px;
              border: 1px solid #f5f6fe;
            ">
            <!-- 添加 flex-grow: 1 使该 div 占据剩余空间 -->
            <div style="flex-grow: 1"></div>

            <router-link to="/cart" style="
                display: flex;
                align-items: center;
                justify-content: center;
                height: 50px;
                padding-right: 20px;
                text-decoration: none; /* 去除默认下划线 */
                color: inherit; /* 继承父元素颜色 */
              ">
              <el-badge :value="bookStore.orderedBooksCount" :max="10" class="badge-item">
                <span class="icon-wrapper">
                  <el-icon style="font-size: 25px">
                    <ShoppingCart />
                  </el-icon>
                </span>
              </el-badge>
            </router-link>

            <div style="
                display: flex;
                align-items: center;
                justify-content: center;
                height: 50px;
                padding-right: 20px;
              ">
              <span class="icon-wrapper">
                <el-icon style="font-size: 25px">
                  <Setting />
                </el-icon>
              </span>
            </div>
            <div style="padding-right: 20px">
              <el-popover placement="bottom" trigger="hover">
                <el-menu mode="vertical">
                  <el-menu-item index="1" @click="handleMenuItemClick(1)">个人中心</el-menu-item>
                  <el-menu-item index="2" @click="handleMenuItemClick(2)">关于我们</el-menu-item>
                  <el-menu-item index="3" @click="handleMenuItemClick_exit(3)">退出登录</el-menu-item>
                </el-menu>

                <template #reference>
                  <el-avatar src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
                </template>
              </el-popover>
            </div>
          </el-header>
        </el-affix>
        <el-main>
          <div class="homePageTitle">
            <h3>首页</h3>
          </div>

          <div class="welcomSign" v-if="isDivVisible">
            <el-icon class="close-icon" @click="welcomSignClose">
              <Close />
            </el-icon>
            <h3>欢迎来到我的第三方图书售卖管理平台</h3>
          </div>

          <el-carousel :interval="5000" arrow="always">
            <el-carousel-item v-for="(item, index) in imageList" :key="index"
              :style="{ backgroundColor: item.bgColor }">
              <img :src="item.src" :alt="item.alt" style="width: 100%; height: 100%"
                @load="handleImageLoad(item.src)" />
            </el-carousel-item>
          </el-carousel>

          <div class="bookStatistics1">
            <el-row :gutter="20">
              <el-col :xs="24" :sm="12" :lg="6">
                <div class="statistic-card">
                  <el-statistic :value="12628">
                    <template #title>
                      <div style="align-items: center">
                        图书总量
                        <el-tooltip effect="dark" content="Number of users who logged into the product in one day"
                          placement="top">
                        </el-tooltip>
                      </div>
                    </template>
                  </el-statistic>
                  <div class="statistic-footer">
                    <div class="footer-item">
                      <span class="green">
                        <el-icon>
                          <Top />
                        </el-icon>
                        10%
                      </span>
                    </div>
                  </div>
                </div>
              </el-col>
              <el-col :xs="24" :sm="12" :lg="6">
                <div class="statistic-card">
                  <el-statistic :value="2250">
                    <template #title>
                      <div style="display: inline-flex; align-items: center">
                        售出总量
                        <el-tooltip effect="dark" content="Number of users who logged into the product in one month"
                          placement="top">
                        </el-tooltip>
                      </div>
                    </template>
                  </el-statistic>
                  <div class="statistic-footer">
                    <div class="footer-item">
                      <span class="green">
                        <el-icon>
                          <Bottom />
                        </el-icon>
                        5%
                      </span>
                    </div>
                  </div>
                </div>
              </el-col>
              <el-col :xs="24" :sm="12" :lg="6">
                <div class="statistic-card">
                  <el-statistic :value="5899" title="New transactions today">
                    <template #title>
                      <div style="display: inline-flex; align-items: center">
                        售出次数
                      </div>
                    </template>
                  </el-statistic>
                  <div class="statistic-footer">
                    <div class="footer-item">
                      <span class=""> Open </span>
                    </div>
                  </div>
                </div>
              </el-col>
              <el-col :xs="24" :sm="12" :lg="6">
                <div class="statistic-card">
                  <el-statistic :value="56" title="New transactions today">
                    <template #title>
                      <div style="display: inline-flex; align-items: center">
                        图书种类
                      </div>
                    </template>
                  </el-statistic>
                  <div class="statistic-footer">
                    <div class="footer-item">
                      <span class=""> New </span>
                    </div>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
          <hr style="height: 1px; border: none; background-color: #f5f6fe" />
          <div class="bookStatistics2">
            <el-row :gutter="20">
              <el-col :xs="24" :sm="24" :md="24" :lg="12">
                <el-card style="border: none" shadow="never">
                  <template #header>
                    <div class="card-header">
                      <h3>最新书籍推荐</h3>
                    </div>
                  </template>
                  <el-tabs v-model="activeName_newbooks" class="demo-tabs" @tab-click="handleClick">
                    <el-tab-pane v-for="(book, index) in newBooks" :key="index" :label="getTabLabel(index)"
                      :name="getName(index)">
                      <el-row>
                        <el-col :span="12">
                          <div>
                            <img style="width: 100%" :src="book.img || '/api/placeholder/400/320'" alt="Book Image" />
                          </div>
                        </el-col>
                        <el-col :span="12">
                          <div class="p-vertically-center">
                            <p>
                              {{ book.description || '暂无描述' }}
                            </p>
                          </div>
                        </el-col>
                      </el-row>
                    </el-tab-pane>
                  </el-tabs>
                </el-card>
              </el-col>
              <el-col :xs="24" :sm="24" :md="24" :lg="12">
                <el-card style="border: none" shadow="never">
                  <template #header>
                    <div class="card-header">
                      <h3>最热书籍推荐</h3>
                    </div>
                  </template>
                  <el-tabs v-model="activeName_hotbooks" class="demo-tabs" @tab-click="handleClick">
                    <el-tab-pane v-for="(book, index) in hotBooks" :key="index" :label="getTabLabel(index)"
                      :name="getName(index)">
                      <el-row>
                        <el-col :span="12">
                          <div>
                            <img style="width: 100%" :src="book.img || '/api/placeholder/400/320'" alt="Book Image" />
                          </div>
                        </el-col>
                        <el-col :span="12">
                          <div class="p-vertically-center">
                            <p>
                              {{ book.description || '暂无描述' }}
                            </p>
                          </div>
                        </el-col>
                      </el-row>
                    </el-tab-pane>
                  </el-tabs>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-main>
        <el-footer style="
            display: flex;
            justify-content: center;
            align-items: center;
            height: 60px;
          ">
          <div>Designed with by XXX</div>
        </el-footer>
      </el-container>
    </el-container>
  </div>
</template>


<script lang="ts" setup>
import { reactive } from "vue";
import { ref } from "vue";
import {
  Reading,
  House,
  Warning,
  Folder,
  Search,
  ArrowRight,
  CaretBottom,
  CaretTop,
  Top,
  Bottom,
  Close,
  Setting,
  ShoppingCart,
} from "@element-plus/icons-vue";
import type { TabsPaneContext } from "element-plus";
import { onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElPopover, ElAvatar, ElMenu, ElMenuItem } from "element-plus";
import carousel1 from "@/assets/carousel1.jpg";
import carousel2 from "@/assets/carousel2.jpg";
import carousel3 from "@/assets/carousel3.jpg";
// 引入 newBook.js 文件中的书籍数据
import newBooks from "@/mock/newBooks.ts";
import hotBooks from "@/mock/hotBooks.ts";
import { useLogout } from "../composables/useLogout";
import { useBookStore } from '../stores/bookStore';

const router = useRouter();
const bookStore = useBookStore();

onMounted(() => {
  const userData = localStorage.getItem("userData");
  if (!userData) {
    // 如果没有获取到数据，跳转到登录页
    router.push("/login");
  }
});

// 定义书籍对象的类型
type Book = {
  title: string;
  img: string;
  price: string;
  notes: string;
  description: string;
};

// 定义 imageItem 类型
interface ImageItem {
  src: string;
  alt: string;
  bgColor: string;
}

const imageList = reactive<ImageItem[]>([
  {
    src: carousel1,
    alt: "图片1",
    bgColor: "#ffffff", // 为每个图片项添加初始背景颜色
  },
  {
    src: carousel2,
    alt: "图片2",
    bgColor: "#ffffff",
  },
  {
    src: carousel3,
    alt: "图片3",
    bgColor: "#ffffff",
  },
]);

const handleImageLoad = (imageUrl: string) => {
  const img = new Image();
  img.src = imageUrl;
  img.onload = async () => {
    try {
      const canvas = document.createElement("canvas");
      canvas.width = img.width;
      canvas.height = img.height;
      const ctx = canvas.getContext("2d");
      if (ctx) {
        ctx.drawImage(img, 0, 0);
        const imageData = ctx.getImageData(0, 0, img.width, img.height);
        const data = imageData.data;
        // 使用 reduce 方法计算平均颜色
        const [r, g, b] = [0, 1, 2].map((channel) =>
          Math.floor(
            data.reduce((acc, value, index) => {
              if ((index - channel) % 4 === 0) {
                return acc + value;
              }
              return acc;
            }, 0) /
            (data.length / 4)
          )
        );
        // 更新当前图片项的背景颜色
        const index = imageList.findIndex((item) => item.src === imageUrl);
        if (index !== -1) {
          imageList[index].bgColor = `rgb(${r},${g},${b})`;
        }
      }
    } catch (error) {
      console.error("Error occurred while processing image:", error);
    }
  };
};

const isCollapse = ref(false);

// 创建一个响应式的布尔变量，初始值设为true，表示div初始是可见的
const isDivVisible = ref(true);

const handleOpen = (key: string, keyPath: string[]) => {
  router.push(key);
  console.log(key, keyPath);
  console.log("open");
};
const handleClose = (key: string, keyPath: string[]) => {
  console.log(key, keyPath);
  console.log("close");
};

const handleSelect = (key: string) => {
  // 根据菜单项的 index 值切换页面

  router.push(key);
};

const input1 = ref("");

const welcomSignClose = () => {
  // 取反isDivVisible的值，实现显示和隐藏的切换
  isDivVisible.value = !isDivVisible.value;
};

const activeName_newbooks = ref("first");
const activeName_hotbooks = ref("first");

const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event);
};

const handleMenuItemClick = (index: number) => {
  console.log(`你点击了选项 ${index}`);
};

const { isLoading, logout } = useLogout();
const handleMenuItemClick_exit = async (index: number) => {
  console.log(`你点击了选项 ${index}`);
  await logout();
};

const getTabLabel = (index: number): string => {
  const labels = ['文学类', '科学类', '医学类', '艺术类'];
  return labels[index];
};

const getName = (index: number): string => {
  const names = ['first', 'second', 'third', 'fourth'];
  return names[index];
};
</script>


<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.el-header {
  /* background-color: gray; */
  background-color: #fff;
}

.el-aside {
  background-color: #fff;
  /* background-color: pink; */
  border: 1px solid #f5f6fe;
}

.el-main {
  background-color: #f5f6fe;
  /* background-color: orange; */
}

.el-menu {
  border-right: none;
}

.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 200px;
  min-height: 400px;
}

.input-with-select .el-input-group__prepend {
  background-color: var(--el-fill-color-blank);
}

.homePageTitle {
  text-align: left;
}

.welcomSign {
  position: relative;
  height: 100px;
  background-color: #fff;
  line-height: 100px;
}

.close-icon {
  position: absolute;
  top: 10px;
  right: 10px;
  cursor: pointer;
  font-size: 16px;
}

.el-carousel {
  padding-top: 20px;
}

.el-carousel__item h3 {
  color: #475669;
  opacity: 0.75;
  line-height: 300px;
  margin: 0;
  text-align: center;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n + 1) {
  background-color: #d3dce6;
}

.el-row {
  margin-bottom: 20px;
}

.el-row:last-child {
  margin-bottom: 0;
}

.el-col {
  border-radius: 4px;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

:global(h2#card-usage ~ .example .example-showcase) {
  background-color: var(--el-fill-color) !important;
}

.el-statistic {
  --el-statistic-content-font-size: 28px;
}

.statistic-card {
  padding: 20px;
  border-radius: 4px;
  background-color: var(--el-bg-color-overlay);
}

.statistic-footer {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
  font-size: 12px;
  color: var(--el-text-color-regular);
  margin-top: 5px;
}

.statistic-footer .footer-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.statistic-footer .footer-item span:last-child {
  display: inline-flex;
  align-items: center;
  margin-left: 4px;
}

.green {
  color: var(--el-color-success);
}

.red {
  color: var(--el-color-error);
}

.bookStatistics1 {
  padding-top: 20px;
}

p {
  margin: 0;
  padding: 0;
  font-size: 14px;
  text-align: left;
}

@media screen and (min-width: 480px) {
  .statistic-card {
    margin-bottom: 20px;
  }
}

@media screen and (min-width: 1200px) {
  .statistic-card {
    margin-bottom: 0px;
  }
}

:deep(.demo-tabs > .el-tabs__content) {
  padding: 32px;
  /* color: #6b778c; */
  font-size: 32px;
  /* font-weight: 600; */
}

/* 去掉标签页导航下方的横线 */
:deep(.demo-tabs .el-tabs__nav-wrap::after) {
  display: none;
}

/* 让标签页导航项可以弹性布局 */
:deep(.demo-tabs .el-tabs__nav) {
  width: 100%;
}

/* 让每个标签页平均占据可用宽度 */
:deep(.demo-tabs .el-tabs__item) {
  flex: 1;
  text-align: center;
}

.card-header {
  text-align: left;
  /* 设置文本左对齐 */
}

.p-vertically-center {
  display: flex;
  /* 使用 Flexbox 布局 */
  flex-direction: column;
  /* 垂直排列子元素 */
  justify-content: center;
  /* 垂直居中 */
  align-items: center;
  /* 水平居中 */
  height: 100%;
  /* 确保容器有高度 */
}

.p-vertically-center p {
  margin: 5px 40px;
  /* 为每个段落添加上下外边距 */
}

/* Vue 3 中使用 ::v-deep 穿透样式，将所有标签页标题文字加粗 */
::v-deep .el-tabs__item {
  font-weight: bold;
}

/* 确保弹出框有最小宽度 */
.el-popover {
  min-width: 120px;
  z-index: 1000;
  /* 确保弹出框显示在最上层 */
}

.badge-item {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.icon-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>